<template>
  <mars-dialog title="分屏对比" :width="260" :top="60" :bottom="60" :left="10">
    <mars-tree checkable :tree-data="layersTree" v-model:expandedKeys="expandedKeys" @check="checkedChange" v-model:checkedKeys="checkedKeys">
      <template #title="{ title }">
        <span class="tree-style" :title="title">{{ title }}</span>
      </template>
    </mars-tree>
  </mars-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue"
import useLifecycle from "@mars/common/uses/use-lifecycle"
import { useWidget } from "@mars/common/store/widget"
import { logInfo } from "@mars/utils/mars-util"
import * as mapWork from "./map"

// 启用map.ts生命周期
useLifecycle(mapWork)

const { updateWidget } = useWidget()

// 取消工具栏高亮
onUnmounted(() => {
  updateWidget("map-compare")
})

const layersTree = ref<any[]>([])
const expandedKeys = ref<string[]>([])
const checkedKeys = ref<string[]>([])

onMounted(() => {
  initTree()
})

// 初始化树构件
function initTree() {
  const showIds = [] // 是显示状态的图层id集合
  const openIds = [] // 展开的树节点id集合（如果不想展开，对应图层配置open:false）

  const result = mapWork.getLayrsTree({
    basemaps: true, // 是否取config.json中的basempas
    filter: function (layer) {
      if (!layer.name) {
        logInfo("未命名图层不加入图层管理", layer)
        return false // 未命名图层不在管理器展示
      }
      return true
    },
    forEach: function (item, layer) {
      item.key = item.id // 树控件api需要的唯一标识
      item.title = item.name || `未命名(${layer.type})` // 树控件api需要的显示文本字段

      item.hasZIndex = layer.hasZIndex // 当前vue绑定使用的属性
      item.hasOpacity = layer.hasOpacity
      item.opacity = layer.opacity ?? 1

      if (item.show) {
        showIds.push(item.id)
      }
      if (item.group && item.open !== false) {
        openIds.push(item.id)
      }
    }
  })
  logInfo("获取到的map图层树", result)

  // 赋予树控件
  layersTree.value = result.tree
  checkedKeys.value = showIds
  expandedKeys.value = openIds
}

// 选中复选框
const checkedChange = (keys: string[], e: any) => {
  const layer = mapWork.getLayerById(e.node.key)
  if (layer) {
    if (!layer.isAdded) {
      mapWork.addLayer(layer)
    }
    if (keys.indexOf(e.node.key) !== -1) {
      if (layer.type === "graphic") {
        layer.eachGraphic((graphic) => (graphic.show = true))
      }
      layer.show = true
      layer.flyTo()
    } else {
      layer.show = false
    }
  }
}
</script>
<style lang="less"></style>
